const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');


const session = require("express-session");
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const uploadRouter = require("./routes/upload");
const orgRouter = require("./routes/organization");
const rulesRouter = require("./routes/rules");
const noticeRouter = require("./routes/notice");
const newsRouter = require("./routes/news");
const activityRouter = require("./routes/activity");

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public', "apidoc")));

app.use(require("cors")());
app.use(require("multer")({ dest: "tmp/" }).array("image"));
// session配置
app.use(
  session({
    secret: "apiserver",
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 1000 * 60 * 30 },
  })
);
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/upload', uploadRouter);
app.use('/org', orgRouter)
app.use('/rules', rulesRouter)
app.use('/notice', noticeRouter)
app.use('/news', newsRouter)
app.use('/activity', activityRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  const Result = require("./utils/result");
  res.json(Result.error(err.message, [{
    status: res.locals.error.status,
    stack: res.locals.error.stack,
  },]));
});

module.exports = app;